const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const startButton = document.getElementById('startButton');
const soundButton = document.getElementById('soundButton');

// 设置画布尺寸
canvas.width = 800;
canvas.height = 600;

// 加载玩家图片
const playerImage = new Image();
playerImage.src = 'images/player.png';

// 游戏状态
let gameStarted = false;
let soundEnabled = true;
let debugMode = false; // 调试模式开关

// 游戏对象
class Player {
    constructor() {
        this.width = 64;
        this.height = 64;
        this.x = 50;
        this.y = 300;
        this.velocityX = 0;
        this.velocityY = 0;
        this.speed = 5;
        this.jumpForce = 15;
        this.gravity = 0.5;
        this.isJumping = false;
    }

    update() {
        // 应用重力
        this.velocityY += this.gravity;
        this.x += this.velocityX;
        this.y += this.velocityY;

        // 简单的地面碰撞检测
        if (this.y + this.height > canvas.height) {
            // 只有当玩家正在下降时才播放着陆音效
            if (this.velocityY > 0 && soundEnabled) soundEffect.land();
            this.y = canvas.height - this.height;
            this.velocityY = 0;
            this.isJumping = false;
        }
        
        // 平台碰撞检测
        platforms.forEach(platform => {
            // 检查水平方向是否有重叠
            if (this.x + this.width > platform.x && this.x < platform.x + platform.width) {
                // 计算玩家上一帧的位置
                const previousY = this.y - this.velocityY;
                
                // 检查玩家是否正在下落
                if (this.velocityY > 0) {
                    // 检查玩家是否从上方穿过平台
                    if (previousY + this.height <= platform.y && this.y + this.height > platform.y) {
                        // 玩家从上方撞击平台
                        this.y = platform.y - this.height;
                        this.velocityY = 0;
                        this.isJumping = false;
                        if (soundEnabled) soundEffect.land();
                        return; // 处理完碰撞后退出循环
                    }
                }
                
                // 检查玩家是否站在平台上
                if (this.y + this.height <= platform.y && this.y + this.height + this.velocityY >= platform.y && this.velocityY >= 0) {
                    this.y = platform.y - this.height;
                    this.velocityY = 0;
                    this.isJumping = false;
                    if (soundEnabled) soundEffect.land();
                    return; // 处理完碰撞后退出循环
                }
                
                // 检查玩家是否从下方撞击平台
                if (this.velocityY < 0 && previousY >= platform.y + platform.height && this.y < platform.y + platform.height) {
                    this.y = platform.y + platform.height;
                    this.velocityY = 0;
                    return; // 处理完碰撞后退出循环
                }
            }
        });

        // 边界检测
        if (this.x < 0) this.x = 0;
        if (this.x + this.width > canvas.width) this.x = canvas.width - this.width;
        
        // 检查是否掉出屏幕底部（游戏结束）
        if (this.y > canvas.height) {
            gameOver();
        }
    }

    draw() {
        // 如果图片已加载，绘制图片；否则绘制原来的像素风格角色
        if (playerImage.complete) {
            ctx.drawImage(playerImage, this.x, this.y, this.width, this.height);
        } else {
            // 绘制像素风格的角色
            ctx.fillStyle = '#ff0000';
            ctx.fillRect(this.x, this.y, this.width, this.height);
            
            // 绘制眼睛
            ctx.fillStyle = '#000000';
            ctx.fillRect(this.x + 40, this.y + 16, 12, 12);
            ctx.fillRect(this.x + 16, this.y + 16, 12, 12);
            
            // 绘制嘴巴
            ctx.fillRect(this.x + 20, this.y + 40, 24, 8);
        }
        
        // 调试模式：绘制玩家边界框（无论使用图片还是像素风格角色）
        if (debugMode) {
            ctx.strokeStyle = '#ff00ff'; // 品红色边界
            ctx.lineWidth = 2;
            ctx.strokeRect(this.x, this.y, this.width, this.height);
            
            // 绘制玩家中心点
            ctx.fillStyle = '#ff00ff';
            ctx.fillRect(this.x + this.width/2 - 2, this.y + this.height/2 - 2, 4, 4);
        }
    }

    jump() {
        if (!this.isJumping) {
            this.velocityY = -this.jumpForce;
            this.isJumping = true;
            if (soundEnabled) soundEffect.jump();
        }
    }
}

// 平台类
class Platform {
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    draw() {
        // 绘制像素风格的平台
        ctx.fillStyle = '#00cc00';
        ctx.fillRect(this.x, this.y, this.width, this.height);
        
        // 添加平台顶部细节
        ctx.fillStyle = '#009900';
        for (let i = 0; i < this.width; i += 8) {
            ctx.fillRect(this.x + i, this.y, 4, 4);
        }
        
        // 调试模式：绘制平台边界框
        if (debugMode) {
            ctx.strokeStyle = '#00ffff'; // 青色边界
            ctx.lineWidth = 2;
            ctx.strokeRect(this.x, this.y, this.width, this.height);
        }
    }
}

// 金币类
class Coin {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 16;
        this.height = 16;
        this.collected = false;
        this.animation = 0;
    }

    update() {
        // 简单的动画效果
        this.animation = (this.animation + 0.1) % (Math.PI * 2);
    }

    draw() {
        if (this.collected) return;
        
        // 绘制旋转的金币
        ctx.save();
        ctx.translate(this.x + this.width/2, this.y + this.height/2);
        ctx.rotate(this.animation);
        
        // 金币主体
        ctx.fillStyle = '#FFD700';
        ctx.fillRect(-this.width/2, -this.height/2, this.width, this.height);
        
        // 金币细节
        ctx.fillStyle = '#FFA500';
        ctx.fillRect(-this.width/2 + 4, -this.height/2 + 4, this.width - 8, this.height - 8);
        
        ctx.restore();
    }
    
    checkCollision(player) {
        if (this.collected) return false;
        
        // 简单的矩形碰撞检测
        if (player.x < this.x + this.width &&
            player.x + player.width > this.x &&
            player.y < this.y + this.height &&
            player.y + player.height > this.y) {
            this.collected = true;
            return true;
        }
        return false;
    }
}

// 创建玩家、平台和金币
const player = new Player();
const platforms = [
    new Platform(0, canvas.height - 20, canvas.width, 20),
    new Platform(200, 400, 100, 20),
    new Platform(400, 300, 100, 20),
    new Platform(600, 200, 100, 20)
];

const coins = [
    new Coin(250, 350),
    new Coin(450, 250),
    new Coin(650, 150),
    new Coin(100, 500),
    new Coin(350, 500),
    new Coin(550, 500)
];

// 游戏状态
let score = 0;

// 键盘输入处理
const keys = {};

window.addEventListener('keydown', (e) => {
    keys[e.key] = true;
    
    // 按'D'键切换调试模式
    if (e.key === 'd' || e.key === 'D') {
        debugMode = !debugMode;
        console.log('调试模式:', debugMode);
    }
});

window.addEventListener('keyup', (e) => {
    keys[e.key] = false;
});

// 游戏主循环
let animationFrameId;

function gameLoop() {
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制背景
drawBackground();

// 处理输入
player.velocityX = 0;
if (keys['ArrowLeft'] || keys['a']) {
    player.velocityX = -player.speed;
}
if (keys['ArrowRight'] || keys['d']) {
    player.velocityX = player.speed;
}
if (keys[' '] || keys['ArrowUp'] || keys['w']) {
    player.jump();
}

// 更新玩家
player.update();

// 更新和绘制平台
platforms.forEach(platform => {
    platform.draw();
});

// 绘制玩家
player.draw();

// 更新和绘制金币
coins.forEach(coin => {
    coin.update();
    coin.draw();
    
    // 检查金币收集
    if (coin.checkCollision(player)) {
        score += 10;
        if (soundEnabled) soundEffect.jump(); // 使用跳跃音效作为收集音效
    }
});

// 绘制分数
ctx.fillStyle = '#FFFFFF';
ctx.font = '20px "Courier New", monospace';
ctx.fillText('分数: ' + score, 20, 30);

    if (gameStarted) {
        animationFrameId = requestAnimationFrame(gameLoop);
    }
}

// 游戏结束函数
function gameOver() {
    gameStarted = false;
    
    // 取消动画帧
    if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
    }
    
    // 显示游戏结束文本
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
    ctx.fillRect(canvas.width/2 - 150, canvas.height/2 - 50, 300, 100);
    
    ctx.fillStyle = '#FFFFFF';
    ctx.font = '30px "Courier New", monospace';
    ctx.textAlign = 'center';
    ctx.fillText('游戏结束', canvas.width/2, canvas.height/2 - 10);
    ctx.font = '20px "Courier New", monospace';
    ctx.fillText('最终分数: ' + score, canvas.width/2, canvas.height/2 + 20);
    ctx.textAlign = 'left';
    
    // 更新按钮文本
    startButton.textContent = "重新开始";
}

// 绘制像素风格背景
function drawBackground() {
    // 绘制渐变背景
    const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
    gradient.addColorStop(0, "#1a1a2e");
    gradient.addColorStop(1, "#16213e");
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制像素星星
    ctx.fillStyle = "#ffffff";
    for (let i = 0; i < 100; i++) {
        const x = Math.random() * canvas.width;
        const y = Math.random() * canvas.height;
        const size = Math.random() * 2;
        ctx.fillRect(x, y, size, size);
    }
}

// 开始游戏
startButton.addEventListener('click', () => {
    if (!gameStarted) {
        gameStarted = true;
        gameLoop();
        startButton.textContent = "重新开始";
    } else {
        // 重新开始游戏
        resetGame();
    }
});

// 重置游戏
function resetGame() {
    // 取消之前的动画帧
    if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
    }
    
    player.x = 50;
    player.y = 300;
    player.velocityX = 0;
    player.velocityY = 0;
    
    // 重置金币
    coins.forEach(coin => {
        coin.collected = false;
    });
    
    // 重置分数
    score = 0;
    
    // 重新开始游戏循环
    gameStarted = true;
    gameLoop();
}

// 音效控制
soundButton.addEventListener('click', () => {
    soundEnabled = !soundEnabled;
    soundButton.textContent = soundEnabled ? "关闭音效" : "开启音效";
});

// 初始绘制背景
drawBackground();